package com.rzico.quartz.job;

import com.rzico.account.entity.CardBill;
import com.rzico.account.entity.Payment;
import com.rzico.account.service.CardBillService;
import com.rzico.account.service.PaymentService;
import com.rzico.basics.entity.Card;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.service.CardService;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.core.entity.SysJob;
import com.rzico.core.service.SysJobService;
import com.rzico.market.entity.Invoice;
import com.rzico.market.service.InvoiceItemService;
import com.rzico.market.service.InvoiceService;
import com.rzico.order.entity.*;
import com.rzico.order.enumx.AskforStatusEnum;
import com.rzico.order.enumx.OrderLogTypeEnum;
import com.rzico.order.enumx.OrderStatusEnum;
import com.rzico.order.service.*;
import com.rzico.util.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  系统所有订单商品开票商品进行项信息同步
 */
public class JDInvoiceTask implements Job {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected SysJobService sysJobService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    protected InvoiceService invoiceService;

    @Autowired
    protected InvoiceItemService invoiceItemService;

    @Autowired
    protected OrderService orderService;

    @Autowired
    protected OrderItemService orderItemService;

    @Autowired
    protected AskforService askforService;

    @Autowired
    protected AskforItemService askforItemService;

    @Autowired
    protected ShippingService shippingService;

    @Autowired
    protected ShippingItemService shippingItemService;

    @Autowired
    protected ReturnService returnService;

    @Autowired
    protected ReturnItemService returnItemService;

    @Autowired
    protected PaymentService paymentService;

    @Autowired
    protected CardService cardService;

    @Autowired
    protected CardBillService cardBillService;

    @Autowired
    protected OrderLogService orderLogService;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String jobId = jobExecutionContext.getTrigger().getKey().getName();
        SysJob sysJob = sysJobService.selectByPrimaryKey(jobId);
        try {
            if (sysJob.getExecStatus().equals(1)) {
                //不能重复执行
                return;
            }
            sysJob.setExecStatus(1);
            sysJob.setJobDesc("开始执行:"+sdf.format(new Date()));
            sysJobService.updateByPrimaryKeySelective(sysJob);

            // 这里开始
            //获取商户号
            String mchId = "";
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("name","葫芦派");
            List<Enterprise> enterpriseList= enterpriseService.selectList(param);
            Long enterpriseId = enterpriseList.get(0).getId();
            /**
             * 先查询已完成订单，已处理过的订单不再处理
             * 判断本订单是否有退货申请，若无退货申请、申请完成或申请取消的话则对订单下的所有商品进项录入，退货申请单状态在进行中不进项录入
             * 再查询已完成订单中所有发货单项（已发送）及退货单项（已退货），去除相同的商品
             */
            Map<String, Object> invoiceParam = new HashMap<String, Object>();
            List<Invoice> allInvoiceList = invoiceService.selectList(invoiceParam);
            List<Long> allInvoiceOrderIdList = new ArrayList<Long>();
            for (Invoice invoice : allInvoiceList) {
                if (!allInvoiceOrderIdList.contains(invoice.getOrderId())) {
                    allInvoiceOrderIdList.add(invoice.getOrderId());
                }
            }
            Map<String, Object> orderParam = new HashMap<String, Object>();
            //状态为已完成
            orderParam.put("orderStatus", OrderStatusEnum.ORDER_STATUS_COMPLETE.getId());
            List<Order> orderList = orderService.selectList(orderParam);
            Map<String, Object> orderParam1 = new HashMap<String, Object>();
            //状态为已评价
            orderParam1.put("orderStatus", OrderStatusEnum.ORDER_STATUS_REVIEWED.getId());
            List<Order> order1List = orderService.selectList(orderParam1);
            List<Order> allOrderList = new ArrayList<Order>();
            allOrderList.addAll(orderList);
            allOrderList.addAll(order1List);
            for (Order order : allOrderList) {
                //筛选过滤保存的订单信息
                if (allInvoiceOrderIdList.contains(order.getId())){
                    continue;
                }
                //查询来源订单是否有退货申请
                boolean askforing = false;//是否有正在进行中的退货申请,无：false,有：true
                Map<String, Object> askforParam = new HashMap<String, Object>();
                askforParam.put("orderId", order.getId());
                List<Askfor> askforList = askforService.selectList(askforParam);
                for (Askfor askfor : askforList) {
                    if (!(askfor.getStatus().equals(AskforStatusEnum.ASKFOR_STATUS_COMPLETE.getId()) || askfor.getStatus().equals(AskforStatusEnum.ASKFOR_STATUS_CANCLEED.getId()))) {
                        askforing = true;
                    }
                }
                if (askforing) {
                    continue;
                }
                //已发货的发货单信息
                Map<String, Object> shipParam = new HashMap<String, Object>();
                shipParam.put("orderId", order.getId());
                List<Shipping> shippingList = shippingService.selectList(shipParam);
                if (0 == shippingList.size()) {
                    continue;
                }
                //退货单信息
                Map<String, Object> returnParam = new HashMap<String, Object>();
                returnParam.put("orderId", order.getId());
                List<Return> returnList = returnService.selectList(returnParam);
                //订单支付信息
                Map<String, Object> paymentMap = new HashMap<String, Object>();
                paymentMap.put("orderId", order.getId());
                paymentMap.put("status", 1);//支付成功
                List<Payment> paymentList = paymentService.selectList(paymentMap);
                //各种支付方式的支付金额map
                Map<String, Object> paymentAmountMap = new HashMap<String, Object>();
                //获取支付的总金额（组合支付与单种方式支付）
                BigDecimal totalPayment = new BigDecimal("0");
                for (Payment payment : paymentList) {
                    if (0 == payment.getAmount().compareTo(payment.getRefund())) {
                        continue;
                    }
                    totalPayment = totalPayment.add(payment.getAmount().subtract(payment.getRefund()));
                    //此卡剩余支付金额
                    paymentAmountMap.put(payment.getSn(), payment.getAmount().subtract(payment.getRefund()));
                }
                //订单完成时间
                Map<String, Object> orderLogMap = new HashMap<String, Object>();
                orderLogMap.put("orderId", order.getId());
                orderLogMap.put("type", OrderLogTypeEnum.ORDER_LOG_TYPE_COMPLETE.getId());
                List<OrderLog> orderLogList = orderLogService.selectList(orderLogMap);
                for (int k = 0; k < shippingList.size(); k ++) {
                    List<ShippingItem> shippingItemList = shippingItemService.getItemList(shippingList.get(k).getId());
                    List<ShippingItem> repeatShippingItemList = new ArrayList<ShippingItem>();//进项商品单项
                    //判断本发货单中是否有商品申请退货
                    for (Return r : returnList) {
                        //发货单及退货单以供应商来划分，判断相同供应商中是否有商品退货，若有商品退货，则过滤掉
                        if (shippingList.get(k).getSupplierId().equals(r.getSupplierId())) {
                            List<ReturnItem> returnItemList = returnItemService.getItemList(r.getId());
                            for (ReturnItem returnItem : returnItemList) {
                                for (ShippingItem shippingItem : shippingItemList) {
                                    if (returnItem.getSn().equals(shippingItem.getSn())) {
                                        repeatShippingItemList.add(shippingItem);
                                    }
                                }
                            }
                        }
                    }
                    shippingItemList.removeAll(repeatShippingItemList);
                    for (int j = 0; j < shippingItemList.size(); j ++) {
                        Map<String, Object> invoiceMap = new HashMap<String, Object>();
                        invoiceMap.put("shippingDate", shippingList.get(k).getCreateDate());
                        invoiceMap.put("sendDate", shippingList.get(k).getModifyDate());
                        if (0 < orderLogList.size()) {
                            invoiceMap.put("completeDate", orderLogList.get(0).getCreateDate());
                        } else {
                            invoiceMap.put("completeDate", order.getModifyDate());
                        }
                        invoiceMap.put("orderId", shippingList.get(k).getOrderId());
                        invoiceMap.put("orderSn", shippingList.get(k).getOrderSn());
                        invoiceMap.put("shippingId", shippingList.get(k).getId());
                        invoiceMap.put("shippingItemId", shippingItemList.get(j).getId());
                        invoiceMap.put("shippingSn", shippingList.get(k).getSn());
                        invoiceMap.put("memberId", shippingList.get(k).getMemberId());
                        invoiceMap.put("supplierId", shippingList.get(k).getSupplierId());
                        invoiceMap.put("deliveryCorp", shippingList.get(k).getDeliveryCorp());
                        invoiceMap.put("tranckNo", shippingList.get(k).getTrackingNo());
                        invoiceMap.put("productId", shippingItemList.get(j).getProductId());
                        invoiceMap.put("productSn", shippingItemList.get(j).getSn());
                        invoiceMap.put("productName", shippingItemList.get(j).getName());
                        invoiceMap.put("productUnit", shippingItemList.get(j).getUnit());
                        invoiceMap.put("productCost", shippingItemList.get(j).getCost());
                        invoiceMap.put("productPrice", shippingItemList.get(j).getPrice());
                        BigDecimal subPrice = shippingItemList.get(j).getPrice().multiply(shippingItemList.get(j).getQuantity());
                        invoiceMap.put("subPrice", subPrice);
                        invoiceMap.put("productQuantity", shippingItemList.get(j).getQuantity());
                        invoiceMap.put("enterpriseId", enterpriseId);
                        Invoice invoice =invoiceService.saveInvoice(invoiceMap);
                        for (int i = 0; i < paymentList.size(); i ++) {
                            //支付记录产生全额退款的不计入金额分摊
                            if (0 == paymentList.get(i).getAmount().compareTo(paymentList.get(i).getRefund())) {
                                continue;
                            }
                            if (StringUtils.isNotEmpty(paymentList.get(i).getPaymentPluginId())) {
                                Map<String, Object> invoiceItemMap = new HashMap<String, Object>();
                                invoiceItemMap.put("invoiceId", invoice.getId());
                                invoiceItemMap.put("method", paymentList.get(i).getMethod());
                                invoiceItemMap.put("pluginId", paymentList.get(i).getPaymentPluginId());
                                invoiceItemMap.put("pluginName", paymentList.get(i).getPaymentPluginName());
                                invoiceItemMap.put("enterpriseId", enterpriseId);
                                if (k == shippingList.size() - 1 && j == shippingItemList.size() - 1) {
                                    if (paymentList.get(i).getPaymentPluginId().equals("cardPayPlugin")) {
                                        Map<String, Object> cardBillMap = new HashMap<String, Object>();
                                        cardBillMap.put("paymentId", paymentList.get(i).getId());
                                        List<CardBill> cardBillList = cardBillService.selectList(cardBillMap);
                                        if (0 == cardBillList.size()) {
                                            continue;
                                        }
                                        Card card = cardService.findById(cardBillList.get(0).getCardId());
                                        invoiceItemMap.put("cardId", card.getId());
                                        invoiceItemMap.put("cardCode", card.getCode());
                                        invoiceItemMap.put("cardMemo", card.getMemo());
                                        invoiceItemMap.put("companyId", card.getCompanyId());
                                        //计算当前支付方式的剩余金额
                                        BigDecimal surplusAmount = (BigDecimal) paymentAmountMap.get(paymentList.get(i).getSn());
                                        invoiceItemMap.put("amount", surplusAmount);

                                    } else {
                                        Member member = order.getMember();
                                        if (null != member.getCompanyId()) {
                                            invoiceItemMap.put("companyId", member.getCompanyId());
                                        } else {
                                            invoiceItemMap.put("companyId", Long.valueOf("0"));
                                        }
                                        //计算当前支付方式的剩余金额
                                        BigDecimal surplusAmount = (BigDecimal) paymentAmountMap.get(paymentList.get(i).getSn());
                                        invoiceItemMap.put("amount", surplusAmount);
                                    }
                                } else {
                                    if (paymentList.get(i).getPaymentPluginId().equals("cardPayPlugin")) {
                                        Map<String, Object> cardBillMap = new HashMap<String, Object>();
                                        cardBillMap.put("paymentId", paymentList.get(i).getId());
                                        List<CardBill> cardBillList = cardBillService.selectList(cardBillMap);
                                        if (0 == cardBillList.size()) {
                                            continue;
                                        }
                                        Card card = cardService.findById(cardBillList.get(0).getCardId());
                                        invoiceItemMap.put("cardId", card.getId());
                                        invoiceItemMap.put("cardCode", card.getCode());
                                        invoiceItemMap.put("cardMemo", card.getMemo());
                                        invoiceItemMap.put("companyId", card.getCompanyId());
                                        BigDecimal payAmount = paymentList.get(i).getAmount().subtract(paymentList.get(i).getRefund());
                                        BigDecimal amout = payAmount.multiply(subPrice).divide(totalPayment, 2, BigDecimal.ROUND_HALF_UP);
                                        invoiceItemMap.put("amount", amout);
                                        //计算当前支付方式的剩余金额
                                        BigDecimal surplusAmount = (BigDecimal) paymentAmountMap.get(paymentList.get(i).getSn());
                                        BigDecimal newSurplusAmount = surplusAmount.subtract(amout);
                                        paymentAmountMap.put(paymentList.get(i).getSn(), newSurplusAmount);

                                    } else {
                                        Member member = order.getMember();
                                        if (null != member.getCompanyId()) {
                                            invoiceItemMap.put("companyId", member.getCompanyId());
                                        } else {
                                            invoiceItemMap.put("companyId", Long.valueOf("0"));
                                        }
                                        BigDecimal payAmount = paymentList.get(i).getAmount().subtract(paymentList.get(i).getRefund());
                                        BigDecimal amout = payAmount.multiply(subPrice).divide(totalPayment, 2, BigDecimal.ROUND_HALF_UP);
                                        invoiceItemMap.put("amount", amout);
                                        //计算当前支付方式的剩余金额
                                        BigDecimal surplusAmount = (BigDecimal) paymentAmountMap.get(paymentList.get(i).getSn());
                                        BigDecimal newSurplusAmount = surplusAmount.subtract(amout);
                                        paymentAmountMap.put(paymentList.get(i).getSn(), newSurplusAmount);
                                    }
                                }
                                invoiceItemService.saveInvoiceItem(invoiceItemMap);
                            }
                        }


                    }
                }
            }
            // end

            sysJob.setExecStatus(0);
            sysJob.setJobDesc("执行成功:"+sdf.format(new Date())+",下次执行:"+sdf.format(jobExecutionContext.getNextFireTime()));
            sysJobService.updateByPrimaryKeySelective(sysJob);
        }
        catch (Exception e) {
            sysJob.setExecStatus(0);
            sysJob.setJobDesc("执行错误:"+sdf.format(new Date()));
            sysJobService.updateByPrimaryKeySelective(sysJob);
        }

    }
}
